<?php
/*
* IKPHP爱客网 安装程序 @copyright (c) 2012-3000 IKPHP All Rights Reserved @author 小麦
* @Email:ikphp@sina.cn
* @小麦 关注 2014年8月9日12:11:41
*/
namespace IKPHP\Apps\Group\Models;

use IKPHP\Common\Models\BaseModel;
use IKPHP\Apps\Group\Models\Group;
use IKPHP\Common\Models\User;

class GroupUsers extends BaseModel {
	
	public $groupid;
	public $userid;
	public $isadmin;
		
	public function getSource() {
		return IK . "group_users";
	}	

	/**
	 * 判断某用户是否加入该组
	 * **/
	public static  function isGroupUser($userid, $groupid) {
		$where = "groupid ='$groupid' AND userid = '$userid'";
		$result = self::findFirst($where);
		if ($result) {
			return $result->toArray();
		} else {
			return false;
		}
	}
	
	public function afterCreate(){
		//更新会员数
		$group = new Group();
 		$oneuser = $group->findFirst("groupid = '$this->groupid'");
 		$oneuser->count_user = $oneuser->count_user+1;
 		$oneuser->save();		
	}
	public function afterDelete(){
		//更新会员数
		$group = new Group();
 		$oneuser = $group->findFirst("groupid = '$this->groupid'");
 		$oneuser->count_user = $oneuser->count_user-1;
 		$oneuser->save();		
	}	
	/**
	 * 根据groupid 获取管理员
	 * **/		
	public static function getAdmins($groupid){
		$where = array(
			'conditions'=> "groupid = '$groupid' AND isadmin=1",
			'order'	=> 'addtime asc',
		);
		$users = array();
		$res = self::find($where);
		if(count($res)>0){
			foreach ($res->toArray() as $item){
				$users[] = User::getOneUser($item['userid']);
			}
		}
		return $users;
	}
	/**
	 * 根据groupid 获取小组的会员
	 * **/		
	public static function getGroupUser($groupid, $limit = ''){
		$where = array(
			'conditions'=> "groupid = '$groupid'",
			'order'	=> 'addtime desc',
		);
		!empty($limit) ? $where['limit'] = 	$limit : '';	
		$users = array();
		$res = self::find($where);
		if(count($res)>0){
			foreach ($res->toArray() as $key=>$item){
				$users[$key] = User::getOneUser($item['userid']);
				$users[$key]['isgroup_admin'] = $item['isadmin']== 1 ? true:false;
			}
		}

		return $users;
	}
	/**
	 * 根据$userid 获取该会员加入的全部小组
	 * **/		
	public static function getGroupByUserid($userid, $limit = ''){
		$where = array(
			'conditions'=> "userid = '$userid'",
			'order'	=> 'addtime desc',
		);
		!empty($limit) ? $where['limit'] = 	$limit : '';	
		$result = array();
		$result = self::find($where); 
		if(count($result)>0)
		{
			return $result->toArray();
		}
		return $result;
	}		
}
